using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemListDispersed : MonoBehaviour
{
    public float startPos;
    public float itemWith = 1080;
    public int space = 20;

    public bool inLerping;

    public int maxIndex = 6;

    public int curIndex;
    // Start is called before the first frame update
    void Start()
    {
       // startPos = (Screen.width - itemWith) / 2;
    }

    private Vector3 m_OldPos;
    bool moving;
    float moveValue;
    bool lerp;
    // Update is called once per frame
    void Update()
    {
        //if (maxIndex == 1) return;

        var vec = transform.localPosition - m_OldPos;
        float dis = Mathf.Abs(vec.x);
        if (dis > 0)
        {
            moveValue = vec.x;
            moving = true;
        }
        if (Input.GetMouseButtonUp(0))
        {
            if (moving)
            {
                lerp = true;
                inLerping = false;
            }
            moving = false;
        }

        if (lerp)
        {
            var localPos = transform.localPosition;
            var x = localPos.x;

            if (!inLerping)
            {
                inLerping = true;
                curIndex += moveValue > 0 ? 1 : -1;

                curIndex = Mathf.Clamp(curIndex, -maxIndex, maxIndex);

                //GameDebug.Log($"curIndex:{curIndex}");
                //curIndex = (int)((x - startPos) / itemWith);

                //if (vec.x < 0)
                //{
                //    float xdis = (x - startPos) - curIndex * itemWith;
                //    if (Mathf.Abs(xdis) > Mathf.Abs(itemWith / 2))
                //        curIndex -= 1;
                //}
                //else
                //{
                //    float xdis = (x - startPos) - curIndex * itemWith;
                //    if (Mathf.Abs(xdis) > Mathf.Abs(itemWith / 2))
                //        curIndex -= 1;
                //}
            }

            float width = itemWith + space;

            float targetPos = startPos + curIndex * width;

            float targetX = Mathf.Lerp(x, targetPos, .1f);
            
            var maxPos = startPos-this.maxIndex * width;
            
            targetX = Mathf.Clamp(targetX, maxPos, startPos);
            //targetX = Mathf.Clamp(targetX, startPos,maxPos );
            
            localPos.x = targetX;

            if (Mathf.Abs(localPos.x - targetPos) < .01f)
            {
                localPos.x = targetPos;
                lerp = false;
                moveValue = 0;
            }
            transform.localPosition = localPos;

        }
        //moving = curMoving;

        m_OldPos = transform.localPosition;
    }
}
